package com.erp.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.shop.domain.ErpSellerStoreCookie;
import com.erp.shop.domain.bo.ErpSellerStoreCookieBo;
import com.erp.shop.domain.vo.ErpSellerStoreCookieVo;
import com.erp.shop.mapper.ErpSellerStoreCookieMapper;
import com.erp.shop.service.IErpSellerStoreCookieService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 店铺cookie信息保存Service业务层处理
 *
 * @author erp
 * @date 2023-12-12
 */
@RequiredArgsConstructor
@Service
public class ErpSellerStoreCookieServiceImpl implements IErpSellerStoreCookieService {

    private final ErpSellerStoreCookieMapper baseMapper;
    @Resource
    RestTemplate restTemplate;
//    @Resource
//    PythonConfig pythonConfig;
    /**
     * 查询店铺cookie信息保存
     */
    @Override
    public ErpSellerStoreCookieVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询店铺cookie信息保存列表
     */
    @Override
    public TableDataInfo<ErpSellerStoreCookieVo> queryPageList(ErpSellerStoreCookieBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSellerStoreCookie> lqw = buildQueryWrapper(bo);
        Page<ErpSellerStoreCookieVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询店铺cookie信息保存列表
     */
    @Override
    public List<ErpSellerStoreCookieVo> queryList(ErpSellerStoreCookieBo bo) {
        LambdaQueryWrapper<ErpSellerStoreCookie> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerStoreCookie> buildQueryWrapper(ErpSellerStoreCookieBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStoreCookie> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getStoreId() != null, ErpSellerStoreCookie::getStoreId, bo.getStoreId());
        lqw.like(StringUtils.isNotBlank(bo.getStoreUserName()), ErpSellerStoreCookie::getStoreUserName, bo.getStoreUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getCookie()), ErpSellerStoreCookie::getCookie, bo.getCookie());
        lqw.eq(StringUtils.isNotBlank(bo.getCookieStatus()), ErpSellerStoreCookie::getCookieStatus, bo.getCookieStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getCookieErrorMsg()), ErpSellerStoreCookie::getCookieErrorMsg, bo.getCookieErrorMsg());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerStoreCookie::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增店铺cookie信息保存
     */
    @Override
    public Boolean insertByBo(ErpSellerStoreCookieBo bo) {
        ErpSellerStoreCookie add = BeanUtil.toBean(bo, ErpSellerStoreCookie.class);
        validEntityBeforeSave(add);

        //查重
        ErpSellerStoreCookie cookie = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreCookie>()
                        .eq(ErpSellerStoreCookie::getStoreId, bo.getStoreId())
        );
        if (ObjectUtils.isNotEmpty(cookie)) {
            add.setId(cookie.getId());
        }
        return baseMapper.insertOrUpdate(add);
    }

    /**
     * 修改店铺cookie信息保存
     */
    @Override
    public Boolean updateByBo(ErpSellerStoreCookieBo bo) {
        ErpSellerStoreCookie update = BeanUtil.toBean(bo, ErpSellerStoreCookie.class);
        validEntityBeforeSave(update);
        update.setCookieStatus("200");
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerStoreCookie entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除店铺cookie信息保存
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R<ErpSellerStoreCookieVo> getInfoByStoreId(Long storeId) {
        ErpSellerStoreCookieVo erpSellerStoreCookieVo = baseMapper.selectVoOne(
                new LambdaQueryWrapper<ErpSellerStoreCookie>()
                        .eq(ErpSellerStoreCookie::getStoreId, storeId)
        );
        return R.ok(erpSellerStoreCookieVo);
    }

    @Override
    public String getCookieByStoreId(Long storeId) {
        ErpSellerStoreCookie erpSellerStoreCookie = baseMapper.selectOne(new LambdaQueryWrapper<ErpSellerStoreCookie>().eq(ErpSellerStoreCookie::getStoreId, storeId));
        if (erpSellerStoreCookie == null)
            return null;
        return erpSellerStoreCookie.getCookie();
    }

    @Override
    public R<Object> setCommission(Long storeId, Long aeProductId, Integer afflicateDiscount) {
        ErpSellerStoreCookie sellerStoreCookie = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreCookie>().eq(ErpSellerStoreCookie::getStoreId, storeId)
        );

        HashMap<String, Object> map = new HashMap<>();
        map.put("commission", afflicateDiscount.toString());
        map.put("productId", aeProductId.toString());
        map.put("cookie_str", sellerStoreCookie.getCookie());
//        System.out.println(map);
        try {
//            ResponseEntity<String> forEntity = restTemplate
//                    .postForEntity("http://47.94.131.193:8000/affiliate/setCommission", map, String.class);
            String body = getReturnBody(JSONObject.toJSONString(map));
            JSONObject bodyJson = JSONObject.parseObject(body);
            String code = bodyJson.getString("code");
            if (!code.equals("200")){
                return R.fail("请求速卖通设置失败");
            }else {
                if (body.contains("errorMsg")){
                    String errorMsg = bodyJson.getJSONObject("data").getJSONObject("data").getString("errorMsg");
                    return R.fail(errorMsg);
                }else {
                    return R.ok("设置成功");
                }
            }

        } catch (Exception e) {
            System.out.println("出现异常"+e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    public R<Object> checkMsg(Long storeId, Integer code, String msg) {
        if (code == 501 && msg.equals("用户cookie过期")) {
            //将店铺cookie设置为失效
            ErpSellerStoreCookie cookie = baseMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerStoreCookie>()
                            .eq(ErpSellerStoreCookie::getStoreId,storeId)
            );
            if (ObjectUtils.isNotNull(cookie)){
                //cookie不为空
                cookie.setCookieStatus("0");
                baseMapper.updateById(cookie);
            }
            return R.fail(msg);
        } else {
            return R.fail();
        }
    }


    private String getReturnBody(String data) {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://47.94.131.193:8000/affiliate/setCommission");
        post.setHeader("Content-Type", "application/json;charset=utf-8");
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-Encoding", "gzip");
        post.setEntity(new StringEntity(data, StandardCharsets.UTF_8));
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(post);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HttpEntity response = httpResponse.getEntity();
        try {
            return EntityUtils.toString(response,StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
